//
// Created by tanke on 23-11-22.
//

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Item {
    int attack_val;
    int defence_val;
};

int compFunc(const void* val1, const void* val2)
{
    const struct Item* item_1 = (const void*)val1;
    const struct Item* item_2 = (const void*)val2;

    if (item_1->attack_val > item_2->attack_val) {
        return -1;
    } else if (item_1->attack_val < item_2->attack_val) {
        return 1;
    } else { // item_1->attack_val == item_2->attack_val
        return item_1->defence_val < item_2->defence_val;
    }
}

int numberOfWeakCharacters(int** properties, int propertiesSize, int* propertiesColSize)
{
    int ret = 0;
    int prev_max_defence_val = 0;
    int prev_attack_val = 0;
    int current_max_defence_val = 0;

    struct Item* itemArray = (struct Item*)malloc(sizeof(struct Item) * propertiesSize);

    for (int i = 0; i < propertiesSize; i ++) {
        itemArray[i].attack_val = properties[i][0];
        itemArray[i].defence_val = properties[i][1];
    }

    qsort(itemArray, propertiesSize, sizeof(struct Item), compFunc);

#if 0
    for (int i = 0; i < propertiesSize; i ++) {
        printf("%d %d\n", itemArray[i].attack_val, itemArray[i].defence_val);
    }
#endif

    prev_attack_val = -1;
    prev_max_defence_val = -1;
    current_max_defence_val = -1;

    for (int i = 0; i < propertiesSize; i ++) {
        if (prev_attack_val == itemArray[i].attack_val) { // 此时应该只更新当前attack值下最大的defence值
            if (current_max_defence_val < itemArray[i].defence_val) {
                current_max_defence_val = itemArray[i].defence_val;
            }
            if (itemArray[i].defence_val < prev_max_defence_val) {
                ret += 1;
            }
        } else { // 来到下一项, attack值小于上一项的attack值
            // 首先更新prev_max_defence_val
            if (prev_max_defence_val < current_max_defence_val) {
                prev_max_defence_val = current_max_defence_val;
            }
            // 然后更新当前attack值下最大的defence值
            current_max_defence_val = itemArray[i].defence_val;
            // 接着更新当前的attack值
            prev_attack_val = itemArray[i].attack_val;
            // 最后判断
            if (itemArray[i].defence_val < prev_max_defence_val) {
                ret += 1;
            }

        }
    }

    return ret;
}

int main(void)
{
    int **nums1 = (int **)malloc(sizeof(int *) * 4);
    for (int i = 0; i < 4; i ++) {
        nums1[i] = (int *)malloc(sizeof(int) * 2);
    }

    nums1[0][0] = 1;
    nums1[0][1] = 1;
    nums1[1][0] = 2;
    nums1[1][1] = 1;
    nums1[2][0] = 2;
    nums1[2][1] = 2;
    nums1[3][0] = 1;
    nums1[3][1] = 2;

    printf("%d\n", numberOfWeakCharacters(nums1, 4, NULL));

    return 0;
}

